import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class GetFileFromUrl {
    /**
     * https://cdn.readmanhwa.com/nhentai/storage/images/1488/20.jpg
     * from 1 to 57
     *
     * Direction:
     *      is -> buf -> os -> file
     */
    public static void get(String outBase, String httpurl, String fileName){
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        try{
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            //connection.setRequestMethod("GET");
            connection.setReadTimeout(15000);
            connection.connect();
//            if(connection.getResponseCode() == 200){
//                is = connection.getInputStream();
//                if(is != null){
//                    br = new BufferedReader(new InputStreamReader(is));
//
//                }
//            }
            is = connection.getInputStream();
            File pic = new File(outBase + fileName);
            if(pic.exists()) pic.delete();
            pic.createNewFile();
            pic.setReadable(true, false);
            pic.setWritable(true, false);
            os = new FileOutputStream(pic);
            byte[] buf = new byte[8 * 1024];
            int len;
            while((len = is.read(buf)) != -1){
                os.write(buf, 0, len);
            }
            os.flush();
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }
}
